const mysql = require('mysql2/promise');
const { app } = require('@electron/remote');

// 数据库连接配置
const dbConfig = {
    host: 'localhost',
    user: 'root',
    password: 'password',
    database: 'photo_album'
};

// 登录函数
async function login() {
    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;
    const errorMessage = document.getElementById('errorMessage');

    if (!username || !password) {
        showError('请输入用户名和密码');
        return;
    }

    try {
        const connection = await mysql.createConnection(dbConfig);
        const [rows] = await connection.execute(
            'SELECT * FROM users WHERE username = ? AND password = ?',
            [username, password]
        );

        if (rows.length > 0) {
            // 登录成功，保存用户信息到localStorage
            localStorage.setItem('currentUser', JSON.stringify({
                id: rows[0].id,
                username: rows[0].username
            }));
            // 跳转到主页
            window.location.href = 'index.html';
        } else {
            showError('用户名或密码错误');
        }

        connection.end();
    } catch (error) {
        console.error('登录失败:', error);
        showError('登录失败: ' + error.message);
    }
}

// 显示注册页面
function showRegister() {
    const container = document.querySelector('.login-container');
    const title = container.querySelector('h2');
    title.textContent = '注册';
    
    const loginBtn = document.querySelector('.btn-login');
    const registerBtn = document.querySelector('.btn-register');
    
    loginBtn.textContent = '注册';
    loginBtn.onclick = register;
    
    registerBtn.textContent = '返回登录';
    registerBtn.onclick = showLogin;
}

// 显示登录页面
function showLogin() {
    const container = document.querySelector('.login-container');
    const title = container.querySelector('h2');
    title.textContent = '登录';
    
    const loginBtn = document.querySelector('.btn-login');
    const registerBtn = document.querySelector('.btn-register');
    
    loginBtn.textContent = '登录';
    loginBtn.onclick = login;
    
    registerBtn.textContent = '注册新账号';
    registerBtn.onclick = showRegister;
}

// 注册函数
async function register() {
    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;

    if (!username || !password) {
        showError('请输入用户名和密码');
        return;
    }

    try {
        const connection = await mysql.createConnection(dbConfig);
        await connection.execute(
            'INSERT INTO users (username, password) VALUES (?, ?)',
            [username, password]
        );

        connection.end();
        showLogin();
        showError('注册成功，请登录', 'success');
    } catch (error) {
        console.error('注册失败:', error);
        showError('注册失败: ' + error.message);
    }
}

// 显示错误信息
function showError(message, type = 'error') {
    const errorDiv = document.getElementById('errorMessage');
    errorDiv.style.display = 'block';
    errorDiv.style.color = type === 'error' ? 'red' : 'green';
    errorDiv.textContent = message;

    // 3秒后自动隐藏
    setTimeout(() => {
        errorDiv.style.display = 'none';
    }, 3000);
}

// 显示重置密码表单
function showResetPassword() {
    const container = document.querySelector('.login-container');
    const title = container.querySelector('h2');
    title.textContent = '重置密码';
    
    const loginBtn = document.querySelector('.btn-login');
    const registerBtn = document.querySelector('.btn-register');
    
    loginBtn.textContent = '确认重置';
    loginBtn.onclick = resetPassword;
    
    registerBtn.textContent = '返回登录';
    registerBtn.onclick = showLogin;
}

// 重置密码功能
async function resetPassword() {
    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;

    if (!username || !password) {
        showError('请输入用户名和新密码');
        return;
    }

    try {
        const connection = await mysql.createConnection(dbConfig);
        // 验证用户名是否存在
        const [users] = await connection.execute(
            'SELECT * FROM users WHERE username = ?',
            [username]
        );

        if (users.length === 0) {
            showError('用户名不存在');
            connection.end();
            return;
        }

        // 更新密码
        await connection.execute(
            'UPDATE users SET password = ? WHERE username = ?',
            [password, username]
        );

        connection.end();
        showLogin();
        showError('密码重置成功，请登录', 'success');
    } catch (error) {
        console.error('重置密码失败:', error);
        showError('重置密码失败: ' + error.message);
    }
}

// 检查用户是否已登录
function checkAuth() {
    const currentUser = localStorage.getItem('currentUser');
    if (!currentUser && window.location.pathname !== '/login.html') {
        window.location.href = 'login.html';
    }
}

// 退出登录
function logout() {
    localStorage.removeItem('currentUser');
    window.location.href = 'login.html';
}